// 加载Express模块
const express = require("express");

// 加载MySQL模块
const mysql = require("mysql");

// 加载bodyParser模块
const bodyParser = require("body-parser");

// 加载MD5模块
const md5 = require("md5");

// 创建MySQL连接池
const pool = mysql.createPool({
  host: "127.0.0.1", //MySQL服务器地址
  port: 3306, //MySQL服务器端口号
  user: "root", //数据库用户的用户名
  password: "", //数据库用户密码
  database: "hy", //数据库名称
  connectionLimit: 20, //最大连接数
  charset: "utf8", //数据库服务器的编码方式
});

// 创建服务器对象
const server = express();

server.use(
  bodyParser.urlencoded({
    extended: false,
  })
);

// 加载CORS模块
const cors = require("cors");
const { error } = require("console");

// 使用CORS中间件
server.use(
  cors({
    origin: ["http://localhost:8080", "http://127.0.0.1:8080"],
  })
);

//用户注册接口
server.post("/register", (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = "SELECT COUNT(user_id) AS count FROM hy_user WHERE username=?";
  pool.query(sql, [username], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = "INSERT hy_user(username,password) VALUES(?,?)";
      pool.query(sql, [username, password], (error, results) => {
        if (error) throw error;
        res.send({ message: "ok", code: 200 });
      });
    } else {
      res.send({ message: "user exists", code: 201 });
    }
  });
});

// 用户登录接口
server.post("/login", (req, res) => {
  //获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
  // console.log(username);
  // console.log(password);
  // SQL语句
  let sql =
    "SELECT user_id,username FROM hy_user WHERE username=? AND password=?";
  pool.query(sql, [username, password], (error, results) => {
    if (error) throw error;
    if (results.length == 0) {
      //登录失败
      res.send({ message: "login failed1", code: 201 });
    } else {
      //登录成功
      res.send({ message: "ok", code: 200, result: results[0] });
    }
  });
});

//获取用户信息的接口
server.post("/user", (req, res) => {
  let user_id = req.body.user_id;
  let sql = "select * from hy_user where user_id =?";
  pool.query(sql, [user_id], (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});

// 获取所有商品分类的接口
server.get("/series", (req, res) => {
  // SQL语句以获取商品分类表的数据
  let sql = "SELECT sid,title FROM product_series ORDER BY sid";
  // 执行SQL语句
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});
// 获取指定分类下包含商品数据的接口
//select * from hy_product where sid=2
server.post("/seriespro", (req, res) => {
  let sid = req.body.sid;
  let sql = "select * from hy_product where sid=?";
  pool.query(sql, [sid], (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});
//获取指定商品详情的接口
server.post("/detail", (req, res) => {
  let pid = req.body.pid;
  let sql = "select * from product_detail where pid=?";
  pool.query(sql, [pid], (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});

//获取指定商品详情图片的接口
server.post("/detimg", (req, res) => {
  let pid = req.body.pid;
  let sql = "select * from detail_img where pid=?";
  pool.query(sql, [pid], (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});

//获取首页轮播图的接口
server.get("/carousel", (req, res) => {
  let sql = "select * from hy_index_carousel ORDER BY hid";
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, results: results });
  });
});

//更新用户头像
server.post("/avatar", (req, res) => {
  let user_id = req.body.user_id;
  let avatar = req.body.avatar;
  if (user_id) {
    let sql = "SELECT COUNT(user_id) AS count FROM hy_user WHERE user_id=?";
    pool.query(sql, [user_id], (error, results) => {
      let count = results[0].count;
      if (count == 0) {
        res.send({ code: 201, message: "用户不存在" });
      } else {
        //更新数据库
        let sql = "UPDATE hy_user SET avatar = ? WHERE user_id = ?;";
        pool.query(sql, [avatar, user_id], (error, results) => {
          if (error) {
            res.json({ code: 201, message: "更新用户头像失败" });
          } else {
            res.send({ code: 200, message: "更新用户头像成功" });
          }
        });
      }
    });
  }
});

// 指定服务器对象监听的端口号
server.listen(3000, () => {
  console.log("server is running...服务器已启动");
});
